/**
 * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package fr.smile.liferay.portlet.news.service.persistence;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import fr.smile.liferay.portlet.news.NoSuchFlagException;
import fr.smile.liferay.portlet.news.model.NewsFlag;
import fr.smile.liferay.portlet.news.model.impl.NewsFlagImpl;
import fr.smile.liferay.portlet.news.model.impl.NewsFlagModelImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the news flag service.
 *
 * <p>
 * Never modify or reference this class directly. Always use {@link NewsFlagUtil} to access the news flag persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
 * </p>
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Brian Wing Shun Chan
 * @see NewsFlagPersistence
 * @see NewsFlagUtil
 * @generated
 */
public class NewsFlagPersistenceImpl extends BasePersistenceImpl<NewsFlag>
	implements NewsFlagPersistence {
	public static final String FINDER_CLASS_NAME_ENTITY = NewsFlagImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
		".List";
	public static final FinderPath FINDER_PATH_FIND_BY_ENTRYID = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findByEntryId",
			new String[] {
				Long.class.getName(),
				
			"java.lang.Integer", "java.lang.Integer",
				"com.liferay.portal.kernel.util.OrderByComparator"
			});
	public static final FinderPath FINDER_PATH_COUNT_BY_ENTRYID = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByEntryId", new String[] { Long.class.getName() });
	public static final FinderPath FINDER_PATH_FETCH_BY_U_E_V = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_ENTITY,
			"fetchByU_E_V",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				Integer.class.getName()
			});
	public static final FinderPath FINDER_PATH_COUNT_BY_U_E_V = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByU_E_V",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				Integer.class.getName()
			});
	public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countAll", new String[0]);

	/**
	 * Caches the news flag in the entity cache if it is enabled.
	 *
	 * @param newsFlag the news flag to cache
	 */
	public void cacheResult(NewsFlag newsFlag) {
		EntityCacheUtil.putResult(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagImpl.class, newsFlag.getPrimaryKey(), newsFlag);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_U_E_V,
			new Object[] {
				new Long(newsFlag.getUserId()), new Long(newsFlag.getEntryId()),
				new Integer(newsFlag.getValue())
			}, newsFlag);
	}

	/**
	 * Caches the news flags in the entity cache if it is enabled.
	 *
	 * @param newsFlags the news flags to cache
	 */
	public void cacheResult(List<NewsFlag> newsFlags) {
		for (NewsFlag newsFlag : newsFlags) {
			if (EntityCacheUtil.getResult(
						NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
						NewsFlagImpl.class, newsFlag.getPrimaryKey(), this) == null) {
				cacheResult(newsFlag);
			}
		}
	}

	/**
	 * Clears the cache for all news flags.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache() {
		CacheRegistryUtil.clear(NewsFlagImpl.class.getName());
		EntityCacheUtil.clearCache(NewsFlagImpl.class.getName());
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
	}

	/**
	 * Clears the cache for the news flag.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache(NewsFlag newsFlag) {
		EntityCacheUtil.removeResult(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagImpl.class, newsFlag.getPrimaryKey());

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_U_E_V,
			new Object[] {
				new Long(newsFlag.getUserId()), new Long(newsFlag.getEntryId()),
				new Integer(newsFlag.getValue())
			});
	}

	/**
	 * Creates a new news flag with the primary key. Does not add the news flag to the database.
	 *
	 * @param flagId the primary key for the new news flag
	 * @return the new news flag
	 */
	public NewsFlag create(long flagId) {
		NewsFlag newsFlag = new NewsFlagImpl();

		newsFlag.setNew(true);
		newsFlag.setPrimaryKey(flagId);

		return newsFlag;
	}

	/**
	 * Removes the news flag with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the news flag to remove
	 * @return the news flag that was removed
	 * @throws com.liferay.portal.NoSuchModelException if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag remove(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return remove(((Long)primaryKey).longValue());
	}

	/**
	 * Removes the news flag with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param flagId the primary key of the news flag to remove
	 * @return the news flag that was removed
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag remove(long flagId)
		throws NoSuchFlagException, SystemException {
		Session session = null;

		try {
			session = openSession();

			NewsFlag newsFlag = (NewsFlag)session.get(NewsFlagImpl.class,
					new Long(flagId));

			if (newsFlag == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + flagId);
				}

				throw new NoSuchFlagException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					flagId);
			}

			return remove(newsFlag);
		}
		catch (NoSuchFlagException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected NewsFlag removeImpl(NewsFlag newsFlag) throws SystemException {
		newsFlag = toUnwrappedModel(newsFlag);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.delete(session, newsFlag);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		NewsFlagModelImpl newsFlagModelImpl = (NewsFlagModelImpl)newsFlag;

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_U_E_V,
			new Object[] {
				new Long(newsFlagModelImpl.getUserId()),
				new Long(newsFlagModelImpl.getEntryId()),
				new Integer(newsFlagModelImpl.getValue())
			});

		EntityCacheUtil.removeResult(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagImpl.class, newsFlag.getPrimaryKey());

		return newsFlag;
	}

	public NewsFlag updateImpl(
		fr.smile.liferay.portlet.news.model.NewsFlag newsFlag, boolean merge)
		throws SystemException {
		newsFlag = toUnwrappedModel(newsFlag);

		boolean isNew = newsFlag.isNew();

		NewsFlagModelImpl newsFlagModelImpl = (NewsFlagModelImpl)newsFlag;

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.update(session, newsFlag, merge);

			newsFlag.setNew(false);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.putResult(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
			NewsFlagImpl.class, newsFlag.getPrimaryKey(), newsFlag);

		if (!isNew &&
				((newsFlag.getUserId() != newsFlagModelImpl.getOriginalUserId()) ||
				(newsFlag.getEntryId() != newsFlagModelImpl.getOriginalEntryId()) ||
				(newsFlag.getValue() != newsFlagModelImpl.getOriginalValue()))) {
			FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_U_E_V,
				new Object[] {
					new Long(newsFlagModelImpl.getOriginalUserId()),
					new Long(newsFlagModelImpl.getOriginalEntryId()),
					new Integer(newsFlagModelImpl.getOriginalValue())
				});
		}

		if (isNew ||
				((newsFlag.getUserId() != newsFlagModelImpl.getOriginalUserId()) ||
				(newsFlag.getEntryId() != newsFlagModelImpl.getOriginalEntryId()) ||
				(newsFlag.getValue() != newsFlagModelImpl.getOriginalValue()))) {
			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_U_E_V,
				new Object[] {
					new Long(newsFlag.getUserId()),
					new Long(newsFlag.getEntryId()),
					new Integer(newsFlag.getValue())
				}, newsFlag);
		}

		return newsFlag;
	}

	protected NewsFlag toUnwrappedModel(NewsFlag newsFlag) {
		if (newsFlag instanceof NewsFlagImpl) {
			return newsFlag;
		}

		NewsFlagImpl newsFlagImpl = new NewsFlagImpl();

		newsFlagImpl.setNew(newsFlag.isNew());
		newsFlagImpl.setPrimaryKey(newsFlag.getPrimaryKey());

		newsFlagImpl.setFlagId(newsFlag.getFlagId());
		newsFlagImpl.setUserId(newsFlag.getUserId());
		newsFlagImpl.setCreateDate(newsFlag.getCreateDate());
		newsFlagImpl.setEntryId(newsFlag.getEntryId());
		newsFlagImpl.setValue(newsFlag.getValue());

		return newsFlagImpl;
	}

	/**
	 * Finds the news flag with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the news flag to find
	 * @return the news flag
	 * @throws com.liferay.portal.NoSuchModelException if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag findByPrimaryKey(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return findByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the news flag with the primary key or throws a {@link fr.smile.liferay.portlet.news.NoSuchFlagException} if it could not be found.
	 *
	 * @param flagId the primary key of the news flag to find
	 * @return the news flag
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag findByPrimaryKey(long flagId)
		throws NoSuchFlagException, SystemException {
		NewsFlag newsFlag = fetchByPrimaryKey(flagId);

		if (newsFlag == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + flagId);
			}

			throw new NoSuchFlagException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				flagId);
		}

		return newsFlag;
	}

	/**
	 * Finds the news flag with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the news flag to find
	 * @return the news flag, or <code>null</code> if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		return fetchByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the news flag with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param flagId the primary key of the news flag to find
	 * @return the news flag, or <code>null</code> if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag fetchByPrimaryKey(long flagId) throws SystemException {
		NewsFlag newsFlag = (NewsFlag)EntityCacheUtil.getResult(NewsFlagModelImpl.ENTITY_CACHE_ENABLED,
				NewsFlagImpl.class, flagId, this);

		if (newsFlag == null) {
			Session session = null;

			try {
				session = openSession();

				newsFlag = (NewsFlag)session.get(NewsFlagImpl.class,
						new Long(flagId));
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (newsFlag != null) {
					cacheResult(newsFlag);
				}

				closeSession(session);
			}
		}

		return newsFlag;
	}

	/**
	 * Finds all the news flags where entryId = &#63;.
	 *
	 * @param entryId the entry id to search with
	 * @return the matching news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findByEntryId(long entryId) throws SystemException {
		return findByEntryId(entryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the news flags where entryId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param entryId the entry id to search with
	 * @param start the lower bound of the range of news flags to return
	 * @param end the upper bound of the range of news flags to return (not inclusive)
	 * @return the range of matching news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findByEntryId(long entryId, int start, int end)
		throws SystemException {
		return findByEntryId(entryId, start, end, null);
	}

	/**
	 * Finds an ordered range of all the news flags where entryId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param entryId the entry id to search with
	 * @param start the lower bound of the range of news flags to return
	 * @param end the upper bound of the range of news flags to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of matching news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findByEntryId(long entryId, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				entryId,
				
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<NewsFlag> list = (List<NewsFlag>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_ENTRYID,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(3 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_NEWSFLAG_WHERE);

			query.append(_FINDER_COLUMN_ENTRYID_ENTRYID_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}

			else {
				query.append(NewsFlagModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(entryId);

				list = (List<NewsFlag>)QueryUtil.list(q, getDialect(), start,
						end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_BY_ENTRYID,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_ENTRYID,
						finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Finds the first news flag in the ordered set where entryId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param entryId the entry id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the first matching news flag
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a matching news flag could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag findByEntryId_First(long entryId,
		OrderByComparator orderByComparator)
		throws NoSuchFlagException, SystemException {
		List<NewsFlag> list = findByEntryId(entryId, 0, 1, orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("entryId=");
			msg.append(entryId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchFlagException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the last news flag in the ordered set where entryId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param entryId the entry id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the last matching news flag
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a matching news flag could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag findByEntryId_Last(long entryId,
		OrderByComparator orderByComparator)
		throws NoSuchFlagException, SystemException {
		int count = countByEntryId(entryId);

		List<NewsFlag> list = findByEntryId(entryId, count - 1, count,
				orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("entryId=");
			msg.append(entryId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchFlagException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the news flags before and after the current news flag in the ordered set where entryId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param flagId the primary key of the current news flag
	 * @param entryId the entry id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the previous, current, and next news flag
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a news flag with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag[] findByEntryId_PrevAndNext(long flagId, long entryId,
		OrderByComparator orderByComparator)
		throws NoSuchFlagException, SystemException {
		NewsFlag newsFlag = findByPrimaryKey(flagId);

		Session session = null;

		try {
			session = openSession();

			NewsFlag[] array = new NewsFlagImpl[3];

			array[0] = getByEntryId_PrevAndNext(session, newsFlag, entryId,
					orderByComparator, true);

			array[1] = newsFlag;

			array[2] = getByEntryId_PrevAndNext(session, newsFlag, entryId,
					orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected NewsFlag getByEntryId_PrevAndNext(Session session,
		NewsFlag newsFlag, long entryId, OrderByComparator orderByComparator,
		boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_NEWSFLAG_WHERE);

		query.append(_FINDER_COLUMN_ENTRYID_ENTRYID_2);

		if (orderByComparator != null) {
			String[] orderByFields = orderByComparator.getOrderByFields();

			if (orderByFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}

		else {
			query.append(NewsFlagModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(entryId);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByValues(newsFlag);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<NewsFlag> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Finds the news flag where userId = &#63; and entryId = &#63; and value = &#63; or throws a {@link fr.smile.liferay.portlet.news.NoSuchFlagException} if it could not be found.
	 *
	 * @param userId the user id to search with
	 * @param entryId the entry id to search with
	 * @param value the value to search with
	 * @return the matching news flag
	 * @throws fr.smile.liferay.portlet.news.NoSuchFlagException if a matching news flag could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag findByU_E_V(long userId, long entryId, int value)
		throws NoSuchFlagException, SystemException {
		NewsFlag newsFlag = fetchByU_E_V(userId, entryId, value);

		if (newsFlag == null) {
			StringBundler msg = new StringBundler(8);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("userId=");
			msg.append(userId);

			msg.append(", entryId=");
			msg.append(entryId);

			msg.append(", value=");
			msg.append(value);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchFlagException(msg.toString());
		}

		return newsFlag;
	}

	/**
	 * Finds the news flag where userId = &#63; and entryId = &#63; and value = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param userId the user id to search with
	 * @param entryId the entry id to search with
	 * @param value the value to search with
	 * @return the matching news flag, or <code>null</code> if a matching news flag could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag fetchByU_E_V(long userId, long entryId, int value)
		throws SystemException {
		return fetchByU_E_V(userId, entryId, value, true);
	}

	/**
	 * Finds the news flag where userId = &#63; and entryId = &#63; and value = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param userId the user id to search with
	 * @param entryId the entry id to search with
	 * @param value the value to search with
	 * @return the matching news flag, or <code>null</code> if a matching news flag could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public NewsFlag fetchByU_E_V(long userId, long entryId, int value,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { userId, entryId, value };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_U_E_V,
					finderArgs, this);
		}

		if (result == null) {
			StringBundler query = new StringBundler(5);

			query.append(_SQL_SELECT_NEWSFLAG_WHERE);

			query.append(_FINDER_COLUMN_U_E_V_USERID_2);

			query.append(_FINDER_COLUMN_U_E_V_ENTRYID_2);

			query.append(_FINDER_COLUMN_U_E_V_VALUE_2);

			query.append(NewsFlagModelImpl.ORDER_BY_JPQL);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(userId);

				qPos.add(entryId);

				qPos.add(value);

				List<NewsFlag> list = q.list();

				result = list;

				NewsFlag newsFlag = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_U_E_V,
						finderArgs, list);
				}
				else {
					newsFlag = list.get(0);

					cacheResult(newsFlag);

					if ((newsFlag.getUserId() != userId) ||
							(newsFlag.getEntryId() != entryId) ||
							(newsFlag.getValue() != value)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_U_E_V,
							finderArgs, newsFlag);
					}
				}

				return newsFlag;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_U_E_V,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (NewsFlag)result;
			}
		}
	}

	/**
	 * Finds all the news flags.
	 *
	 * @return the news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the news flags.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of news flags to return
	 * @param end the upper bound of the range of news flags to return (not inclusive)
	 * @return the range of news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findAll(int start, int end) throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Finds an ordered range of all the news flags.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of news flags to return
	 * @param end the upper bound of the range of news flags to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of news flags
	 * @throws SystemException if a system exception occurred
	 */
	public List<NewsFlag> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<NewsFlag> list = (List<NewsFlag>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;
			String sql = null;

			if (orderByComparator != null) {
				query = new StringBundler(2 +
						(orderByComparator.getOrderByFields().length * 3));

				query.append(_SQL_SELECT_NEWSFLAG);

				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);

				sql = query.toString();
			}
			else {
				sql = _SQL_SELECT_NEWSFLAG.concat(NewsFlagModelImpl.ORDER_BY_JPQL);
			}

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				if (orderByComparator == null) {
					list = (List<NewsFlag>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);
				}
				else {
					list = (List<NewsFlag>)QueryUtil.list(q, getDialect(),
							start, end);
				}
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_ALL,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs,
						list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the news flags where entryId = &#63; from the database.
	 *
	 * @param entryId the entry id to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByEntryId(long entryId) throws SystemException {
		for (NewsFlag newsFlag : findByEntryId(entryId)) {
			remove(newsFlag);
		}
	}

	/**
	 * Removes the news flag where userId = &#63; and entryId = &#63; and value = &#63; from the database.
	 *
	 * @param userId the user id to search with
	 * @param entryId the entry id to search with
	 * @param value the value to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByU_E_V(long userId, long entryId, int value)
		throws NoSuchFlagException, SystemException {
		NewsFlag newsFlag = findByU_E_V(userId, entryId, value);

		remove(newsFlag);
	}

	/**
	 * Removes all the news flags from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	public void removeAll() throws SystemException {
		for (NewsFlag newsFlag : findAll()) {
			remove(newsFlag);
		}
	}

	/**
	 * Counts all the news flags where entryId = &#63;.
	 *
	 * @param entryId the entry id to search with
	 * @return the number of matching news flags
	 * @throws SystemException if a system exception occurred
	 */
	public int countByEntryId(long entryId) throws SystemException {
		Object[] finderArgs = new Object[] { entryId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_ENTRYID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_NEWSFLAG_WHERE);

			query.append(_FINDER_COLUMN_ENTRYID_ENTRYID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(entryId);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_ENTRYID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the news flags where userId = &#63; and entryId = &#63; and value = &#63;.
	 *
	 * @param userId the user id to search with
	 * @param entryId the entry id to search with
	 * @param value the value to search with
	 * @return the number of matching news flags
	 * @throws SystemException if a system exception occurred
	 */
	public int countByU_E_V(long userId, long entryId, int value)
		throws SystemException {
		Object[] finderArgs = new Object[] { userId, entryId, value };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_U_E_V,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_COUNT_NEWSFLAG_WHERE);

			query.append(_FINDER_COLUMN_U_E_V_USERID_2);

			query.append(_FINDER_COLUMN_U_E_V_ENTRYID_2);

			query.append(_FINDER_COLUMN_U_E_V_VALUE_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(userId);

				qPos.add(entryId);

				qPos.add(value);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_U_E_V,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the news flags.
	 *
	 * @return the number of news flags
	 * @throws SystemException if a system exception occurred
	 */
	public int countAll() throws SystemException {
		Object[] finderArgs = new Object[0];

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_NEWSFLAG);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
					count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the news flag persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.fr.smile.liferay.portlet.news.model.NewsFlag")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<NewsFlag>> listenersList = new ArrayList<ModelListener<NewsFlag>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<NewsFlag>)InstanceFactory.newInstance(
							listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	public void destroy() {
		EntityCacheUtil.removeCache(NewsFlagImpl.class.getName());
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST);
	}

	@BeanReference(type = NewsEntryPersistence.class)
	protected NewsEntryPersistence newsEntryPersistence;
	@BeanReference(type = NewsFlagPersistence.class)
	protected NewsFlagPersistence newsFlagPersistence;
	@BeanReference(type = ResourcePersistence.class)
	protected ResourcePersistence resourcePersistence;
	@BeanReference(type = UserPersistence.class)
	protected UserPersistence userPersistence;
	private static final String _SQL_SELECT_NEWSFLAG = "SELECT newsFlag FROM NewsFlag newsFlag";
	private static final String _SQL_SELECT_NEWSFLAG_WHERE = "SELECT newsFlag FROM NewsFlag newsFlag WHERE ";
	private static final String _SQL_COUNT_NEWSFLAG = "SELECT COUNT(newsFlag) FROM NewsFlag newsFlag";
	private static final String _SQL_COUNT_NEWSFLAG_WHERE = "SELECT COUNT(newsFlag) FROM NewsFlag newsFlag WHERE ";
	private static final String _FINDER_COLUMN_ENTRYID_ENTRYID_2 = "newsFlag.entryId = ?";
	private static final String _FINDER_COLUMN_U_E_V_USERID_2 = "newsFlag.userId = ? AND ";
	private static final String _FINDER_COLUMN_U_E_V_ENTRYID_2 = "newsFlag.entryId = ? AND ";
	private static final String _FINDER_COLUMN_U_E_V_VALUE_2 = "newsFlag.value = ?";
	private static final String _ORDER_BY_ENTITY_ALIAS = "newsFlag.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No NewsFlag exists with the primary key ";
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No NewsFlag exists with the key {";
	private static Log _log = LogFactoryUtil.getLog(NewsFlagPersistenceImpl.class);
}